package com.jdy.haoduoaiteacher.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources.NotFoundException;
import android.graphics.drawable.ColorDrawable;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;

import com.ycsj.goldmedalnewconcept.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class YearMonthDayPicker2 {
  private static final int MIN_YEAR = 1970;

  private static final int MAX_YEAR = 2099;

  private static final String[] PICKER_DISPLAY_MONTHS_NAMES = new String[] {
      "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };

  private static final String[] MONTHS = new String[] { "January", "February",
      "March", "April", "May", "June", "July", "August", "September",
      "October", "November", "December" };

  private View view;
  private Activity activity;
  private AlertDialog.Builder builder;
  private AlertDialog pickerDialog;
  private boolean build = false;
  private NumberPicker monthNumberPicker;
  private NumberPicker yearNumberPicker;
  private NumberPicker dayNumberPicker;
  private Calendar todayCalendarInstance;

  private Calendar selectedCalendarInstance;

  /**
   * Instantiates a new month year picker.
   * 
   * @param activity
   *          the activity
   */
  public YearMonthDayPicker2(Activity activity) {
    this.activity = activity;

    final Context contextThemeWrapper = new ContextThemeWrapper(this.activity,
        R.style.cust_dialog);

    LayoutInflater inflater = activity.getLayoutInflater();
    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

    this.view = localInflater
        .inflate(R.layout.year_month_day_picker_view, null);

  }

  /**
   * Builds the month year alert dialog.
   * 
   * @param positiveButtonListener
   *          the positive listener
   * @param negativeButtonListener
   *          the negative listener
   */
  public void build(DialogInterface.OnClickListener positiveButtonListener,
      DialogInterface.OnClickListener negativeButtonListener) {
    this.build(-1, -1, -1, positiveButtonListener, negativeButtonListener);
  }

  private int currentYear;

  private int currentMonth;

  private int currentDay;

  /**
   * Builds the month year alert dialog.
   * 
   * @param selectedMonth
   *          the selected month 0 to 11 (sets current moth if invalid value)
   * @param selectedYear
   *          the selected year 1970 to 2099 (sets current year if invalid
   *          value)
   * @param positiveButtonListener
   *          the positive listener
   * @param negativeButtonListener
   *          the negative listener
   */
  public void build(int selectedDay, int selectedMonth, int selectedYear,
      DialogInterface.OnClickListener positiveButtonListener,
      DialogInterface.OnClickListener negativeButtonListener) {

    todayCalendarInstance = Calendar.getInstance();
    selectedCalendarInstance = (Calendar) todayCalendarInstance.clone();
    int maxDayOfMonth = todayCalendarInstance
        .getActualMaximum(Calendar.DAY_OF_MONTH);
    currentMonth = todayCalendarInstance.get(Calendar.MONTH);
    currentYear = todayCalendarInstance.get(Calendar.YEAR);
    currentDay = todayCalendarInstance.get(Calendar.DAY_OF_MONTH);

    if (selectedDay > maxDayOfMonth || selectedDay < 1) {
      selectedDay = currentDay;
    }

    if (selectedMonth > 11 || selectedMonth < -1) {
      selectedMonth = currentMonth;
    }

    if (selectedYear < MIN_YEAR || selectedYear > MAX_YEAR) {
      selectedYear = currentYear;
    }

    if (selectedMonth == -1) {
      selectedMonth = currentMonth;
    }

    if (selectedYear == -1) {
      selectedYear = currentYear;
    }

    if (selectedDay == -1) {
      selectedDay = currentDay;
    }

    builder = new AlertDialog.Builder(new ContextThemeWrapper(activity,
        R.style.cust_dialog));
    builder.setView(view);

    monthNumberPicker = (NumberPicker) view
        .findViewById(R.id.monthNumberPicker);
    monthNumberPicker.setDisplayedValues(PICKER_DISPLAY_MONTHS_NAMES);

    monthNumberPicker.setMinValue(0);
    monthNumberPicker.setMaxValue(MONTHS.length - 1);

    yearNumberPicker = (NumberPicker) view.findViewById(R.id.yearNumberPicker);
    yearNumberPicker.setMinValue(MIN_YEAR);
    yearNumberPicker.setMaxValue(MAX_YEAR);

    dayNumberPicker = (NumberPicker) view.findViewById(R.id.dayNumberPicker);
    dayNumberPicker.setMinValue(1);
    dayNumberPicker.setMaxValue(maxDayOfMonth);

    monthNumberPicker.setValue(selectedMonth);
    yearNumberPicker.setValue(selectedYear);
    dayNumberPicker.setValue(selectedDay);

    monthNumberPicker
        .setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
    yearNumberPicker
        .setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
    dayNumberPicker
        .setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

    yearNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {

      @Override
      public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        // TODO Auto-generated method stub
        selectedCalendarInstance.add(Calendar.YEAR, newVal - oldVal);
        int maxDaysOftheMonth = selectedCalendarInstance
            .getActualMaximum(Calendar.DAY_OF_MONTH);
        dayNumberPicker.setMaxValue(maxDaysOftheMonth);
        pickerDialog.setTitle(getSelectedDate());
        view.invalidate();
      }
    });

    monthNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {

      @Override
      public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        // TODO Auto-generated method stub

        // selectedCalendarInstance.set(Calendar.MONTH,newVal);
        selectedCalendarInstance.add(Calendar.MONTH, newVal - oldVal);

        int maxDaysOftheMonth = selectedCalendarInstance
            .getActualMaximum(Calendar.DAY_OF_MONTH);
        dayNumberPicker.setMaxValue(maxDaysOftheMonth);
        int currentSelectedDay = dayNumberPicker.getValue();
        if (currentSelectedDay > maxDaysOftheMonth)
          dayNumberPicker.setValue(maxDaysOftheMonth);
        pickerDialog.setTitle(getSelectedDate());
        view.invalidate();
      }
    });

    dayNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {

      @Override
      public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        // TODO Auto-generated method stub
        selectedCalendarInstance.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
        pickerDialog.setTitle(getSelectedDate());
        view.invalidate();
      }
    });

    builder.setTitle(getSelectedDate());
    builder.setPositiveButton(
        activity.getString(R.string.control_button_cancel),
        negativeButtonListener);
    builder.setNegativeButton(
        activity.getString(R.string.control_button_submit),
        positiveButtonListener);
    setDividerColor();
    build = true;
    pickerDialog = builder.create();

  }

  public void setDividerColor() {
    setDividerColor(yearNumberPicker);
    setDividerColor(monthNumberPicker);
    setDividerColor(dayNumberPicker);
  }

  /**
   * Set divider color of numberpicker using reflection.
   * 
   * @param picker
   */
  private void setDividerColor(NumberPicker picker) {
    java.lang.reflect.Field[] pickerFields = NumberPicker.class
        .getDeclaredFields();
    for (java.lang.reflect.Field pf : pickerFields) {
      if (pf.getName().equals("mSelectionDivider")) {
        pf.setAccessible(true);
        try {
          // pf.set(picker, getResources().getColor(R.color.my_orange));
          // Log.v(TAG,"here");
          ColorDrawable colorDrawable = new ColorDrawable(this.activity
              .getResources().getColor(R.color.setting_top_background));
          pf.set(picker, colorDrawable);
        } catch (IllegalArgumentException e) {
          e.printStackTrace();
        } catch (NotFoundException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        }
        break;
      }
    }
    // }
  }

  /**
   * Get pickerDialog
   * 
   * @return
   */
  public AlertDialog getDialog() {
    return pickerDialog;
  }

  /**
   * Show month year picker dialog.
   */
  public void show() {
    if (build) {
      pickerDialog.show();
    } else {
      throw new IllegalStateException("Build picker before use");
    }
  }

  /**
   * Gets the selected month.
   * 
   * @return the selected month
   */
  public int getSelectedMonth() {
    return monthNumberPicker.getValue();
  }

  /**
   * Gets the selected month name.
   * 
   * @return the selected month name
   */
  public String getSelectedMonthName() {
    return MONTHS[monthNumberPicker.getValue()];
  }

  /**
   * Gets the selected month name.
   * 
   * @return the selected month short name i.e Jan, Feb ...
   */
  public String getSelectedMonthShortName() {
    return PICKER_DISPLAY_MONTHS_NAMES[monthNumberPicker.getValue()];
  }

  /**
   * Gets the selected year.
   * 
   * @return the selected year
   */
  public int getSelectedYear() {
    return yearNumberPicker.getValue();
  }

  /**
   * Gets the selected day.
   * 
   * @return the selected day
   */
  public int getSelectedDay() {
    return dayNumberPicker.getValue();
  }

  /**
   * Gets the current year.
   * 
   * @return the current year
   */
  public int getCurrentYear() {
    return currentYear;
  }

  /**
   * Gets the current month.
   * 
   * @return the current month
   */
  public int getCurrentMonth() {
    return currentMonth;
  }

  /**
   * Gets the current day
   * 
   * @return the current day
   */
  public int getCurrentDay() {
    return currentDay;
  }

  /**
   * Gets the selected calendar.
   * 
   * @return
   */
  public String getSelectedDate() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String strDate = sdf.format(selectedCalendarInstance.getTime());
    return strDate;
  }

  /**
   * 年/月/日
   * 
   * @return
   */
  public String getSelectedDate2() {

    String strDate = selectedCalendarInstance.get(Calendar.YEAR) + "年"
        + (selectedCalendarInstance.get(Calendar.MONTH) + 1) + "月"// 从0计算
        + selectedCalendarInstance.get(Calendar.DAY_OF_MONTH) + "日";

    return strDate;
  }

  public String getSelectDateString() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String strDate = sdf.format(selectedCalendarInstance.getTime());
    return strDate;

  }

  /**
   * Sets the day value changed listener.
   * 
   * @param valueChangeListener
   *          the new day value changed listener
   */
  public void setDayValueChangedListener(
      OnValueChangeListener valueChangeListener) {
    dayNumberPicker.setOnValueChangedListener(valueChangeListener);
  }

  /**
   * Sets the month value changed listener.
   * 
   * @param valueChangeListener
   *          the new month value changed listener
   */
  public void setMonthValueChangedListener(
      OnValueChangeListener valueChangeListener) {
    monthNumberPicker.setOnValueChangedListener(valueChangeListener);
  }

  /**
   * Sets the year value changed listener.
   * 
   * @param valueChangeListener
   *          the new year value changed listener
   */
  public void setYearValueChangedListener(
      OnValueChangeListener valueChangeListener) {
    yearNumberPicker.setOnValueChangedListener(valueChangeListener);
  }

  /**
   * Sets the day wrap selector wheel.
   * 
   * @param wrapSelectorWheel
   *          the new day wrap selector wheel
   * 
   */
  public void setDayWrapSelectorWheel(boolean wrapSelectorWheel) {
    dayNumberPicker.setWrapSelectorWheel(wrapSelectorWheel);
  }

  /**
   * Sets the month wrap selector wheel.
   * 
   * @param wrapSelectorWheel
   *          the new month wrap selector wheel
   */
  public void setMonthWrapSelectorWheel(boolean wrapSelectorWheel) {
    monthNumberPicker.setWrapSelectorWheel(wrapSelectorWheel);
  }

  /**
   * Sets the year wrap selector wheel.
   * 
   * @param wrapSelectorWheel
   *          the new year wrap selector wheel
   */
  public void setYearWrapSelectorWheel(boolean wrapSelectorWheel) {
    yearNumberPicker.setWrapSelectorWheel(wrapSelectorWheel);
  }

}
